package com.cll.pmis.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cll.pmis.common.Constants;
import com.cll.pmis.common.Result;
import com.cll.pmis.common.annotation.HasPerms;
import com.cll.pmis.common.security.SecurityContext;
import com.cll.pmis.common.validator.ValidatorUtils;
import com.cll.pmis.common.validator.group.Insert;
import com.cll.pmis.entity.Input;
import com.cll.pmis.entity.InputDrug;
import com.cll.pmis.service.IInputDrugService;
import com.cll.pmis.service.IInputService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 药品入库
 * </p>
 *
 * @author chenliangliang
 * @since 2018-06-18
 */
@RestController
@RequestMapping("/input")
public class InputController {


    private IInputService inputService;
    private IInputDrugService inputDrugService;
    private JmsTemplate jmsTemplate;

    protected InputController(IInputService inputService, IInputDrugService inputDrugService, JmsTemplate jmsTemplate) {
        this.inputService = inputService;
        this.inputDrugService = inputDrugService;
        this.jmsTemplate = jmsTemplate;
    }


    /**
     * 药品入库记录
     */
    @HasPerms("input:insert")
    @PostMapping("/add")
    public Result add(@RequestBody Input input) {

        System.out.println(input);
//        System.out.println(inputJson);
//        JSONObject jsonObject = JSONObject.parseObject(inputJson);
//        String type = jsonObject.getString("type");
//        String provider = jsonObject.getString("provider");
//        String remark = jsonObject.getString("remark");
//
//        List<InputDrug> inputDrugs = jsonObject.getJSONArray("list").toJavaList(InputDrug.class);
//
//        Input input = new Input();
//        input.setType(type);
//        input.setRemark(remark);
//        input.setProvider(provider);
//        input.setList(inputDrugs);

        ValidatorUtils.validateEntity(input, Insert.class);

        for (InputDrug inputDrug : input.getList()) {
//            Date ptime = CommonUtil.parseDate(inputDrug.getPtime());
//            if (ptime == null) {
//                return Result.paramError("生产日期格式错误");
//            }
//            Date otime = CommonUtil.parseDate(inputDrug.getOtime());
//            if (otime == null) {
//                return Result.paramError("过期时间格式错误");
//            }
            ValidatorUtils.validateEntity(inputDrug, Insert.class);
//            inputDrug.setProductTime(ptime);
//            inputDrug.setOverTime(otime);
        }

        inputService.createInput(SecurityContext.getUsername(), input);
        return Result.ok("");
    }

    @GetMapping("/list")
    public Result list(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                       @RequestParam(value = "pageSize", required = false) Integer pageSize,
                       @RequestParam(value = "query", required = false) String query,
                       @RequestParam(value = "type", required = false) String type) {

        if (pageIndex == null || pageIndex < 1) {
            pageIndex = 1;
        }

        if (pageSize == null || pageSize < 1) {
            pageSize = 4;
        }

        Integer inputId = null;
        if (StringUtils.isNotEmpty(query)) {
            try {
                inputId = Integer.valueOf(query);
            } catch (Exception e) {
                //ignore
            }
        }

        Page<Input> page = inputService.selectPage(new Page<>(pageIndex, pageSize,"id",false),
                new EntityWrapper<Input>().like(inputId != null, "id", String.valueOf(inputId))
                        .eq(StringUtils.isNotEmpty(type), "type", type));
        return Result.ok(page);
    }


    @GetMapping("/delete")
    public Result delete(@RequestParam("inputId") Integer inputId) {
        if (inputId == null) {
            return Result.paramError();
        }
        //如果已审核,则不能删除
        Input input = inputService.selectById(inputId);
        if (input == null) {
            return Result.fail("该入库单不存在");
        }

        if (input.getStatus() > Constants.INPUT_STATUS_UNCHECK) {
            return Result.fail("该入库单已审核通过,不能删除");
        }
        return inputService.deleteById(inputId) ? Result.ok("") : Result.deleteError();
    }

    @HasPerms("input:check")
    @GetMapping("/check")
    public Result checkInput(@RequestParam("inputId") Integer inputId) {

        Input input = inputService.selectOne(new EntityWrapper<Input>().eq("id", inputId));
        if (input == null) {
            return Result.fail("该入库单不存在，请检查入库单号是否合法");
        }

        if (input.getStatus() != Constants.INPUT_STATUS_UNCHECK) {
            return Result.fail("已审核通过");
        }

        Input in = new Input();
        in.setId(inputId);
        in.setStatus(Constants.INPUT_STATUS_CHECKED);
        in.setUpdateTime(new Date());

        if (inputService.updateById(in)) {
            jmsTemplate.convertAndSend(Constants.INPUT_DRUG_QUEUE, inputId);
            return Result.ok("");
        }
        return Result.fail("审核失败");
    }


    @HasPerms("input:select")
    @GetMapping("/detail")
    public Result inputDetail(@RequestParam("inputId") Integer inputId) {
        if (inputId == null) {
            return Result.paramError();
        }
        Input input = inputService.selectOne(new EntityWrapper<Input>().eq("id", inputId));

        if (input == null) {
            return Result.fail("该入库单不存在");
        }

        List<InputDrug> inputDrugs = inputDrugService.selectList(new EntityWrapper<InputDrug>().eq("input_id", inputId));
        input.setList(inputDrugs);

        return Result.ok(input);

    }


}

